package com.wxd.woff.table;

import com.wxd.woff.AbstractOTFDataStream;
import com.wxd.woff.AbstractWoffTable;
import com.wxd.woff.ByteBufferOTFDataStream;
import com.wxd.woff.WoffFont;

import java.io.IOException;
import java.util.Arrays;

/**
 * loca table
 * Created with IntelliJ IDEA.
 *
 * @author: wangxindong
 * @date: 2018/9/1-23:10
 */
public class IndexToLocationTable extends AbstractWoffTable {

    public static final String TAG = "loca";

    /**
     * 2 byte
     */
    private static final short SHORT_OFFSETS = 0;

    /**
     * 4 byte
     */
    private static final short LONG_OFFSETS = 1;

    private long[] offsets;

    public IndexToLocationTable(WoffFont woffFont) {
        super(woffFont);
    }

    @Override
    public void read(WoffFont woffFont, AbstractOTFDataStream stream) throws IOException {
        HeaderTable head = woffFont.getHeaderTable();
        int numGlyphs = woffFont.getNumberOfGlyphs();
        stream.seek(offset);
        byte[] fontData = stream.read(compLength);
        byte[] inflateFont = inflateFontData(fontData);
        AbstractOTFDataStream data = new ByteBufferOTFDataStream(inflateFont);
        offsets = new long[numGlyphs + 1];
        for (int i = 0; i < numGlyphs + 1; i++) {
            if (head.getIndexToLocFormat() == SHORT_OFFSETS) {
                offsets[i] = data.readUnsignedShort() * 2;
            } else if (head.getIndexToLocFormat() == LONG_OFFSETS) {
                offsets[i] = data.readUnsignedInt();
            } else {
                throw new IOException("Error:TTF.loca unknown offset format.");
            }
        }
    }

    public long[] getOffsets() {
        return offsets;
    }

    public void setOffsets(long[] offsets) {
        this.offsets = offsets;
    }

    @Override
    public String toString() {
        return "AbstractWoffTable{" +
                "tag='" + tag + '\'' +
                ", offset=" + offset +
                ", compLength=" + compLength +
                ", origLength=" + origLength +
                ", origChecksum=" + origChecksum +
                ", offsets=" + Arrays.toString(offsets) +
                '}';
    }
}
